package com.wang.pool.config;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: wangning
 * @date: 2024/1/15 14:29
 */
@Configuration
@EnableConfigurationProperties(CustomThreadProperties.class)
@RequiredArgsConstructor
@ConditionalOnProperty(name = "custom.threadPool.enabled", havingValue = "true")
public class CustomThreadPoolConfiguration {

    private final CustomThreadProperties customThreadProperties;

    @Bean
    public ThreadPoolTaskExecutor customThreadPoolExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数值
        executor.setCorePoolSize(customThreadProperties.getCorePoolSize());
        // 最大线程数值
        executor.setMaxPoolSize(customThreadProperties.getMaxPoolSize());
        // 存活时间，单位：s
        executor.setKeepAliveSeconds(customThreadProperties.getKeepAliveTime());
        // 线程名称前缀
        executor.setThreadNamePrefix(customThreadProperties.getThread_name_prefix());
        // 缓冲队列大小
        executor.setQueueCapacity(customThreadProperties.getQueueCapacity());
        // 拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        // 初始化
        executor.initialize();
        System.out.println("++++++++++++++++++++++++===================>>>>>>>>>>>>>加载成功");
        System.out.println("++++++++++++++++++++++++===================>>>>>>>>>>>>>加载成功");
        System.out.println("++++++++++++++++++++++++===================>>>>>>>>>>>>>加载成功");
        System.out.println("++++++++++++++++++++++++===================>>>>>>>>>>>>>加载成功");
        System.out.println("++++++++++++++++++++++++===================>>>>>>>>>>>>>加载成功");
        System.out.println("++++++++++++++++++++++++===================>>>>>>>>>>>>>加载成功");
        System.out.println("++++++++++++++++++++++++===================>>>>>>>>>>>>>加载成功");
        System.out.println("++++++++++++++++++++++++===================>>>>>>>>>>>>>加载成功");
        return executor;
    }

}
